package com.naiterui.ehp.bs.wechat.service.impl;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.constants.CommonConstant;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bs.wechat.config.WeChatConfig;
import com.naiterui.ehp.bs.wechat.protocol.result.JsTicket;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.service.IJsApiService;
import com.naiterui.ehp.bs.wechat.utils.SHA1;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;
import com.naiterui.ehp.bs.wechat.vo.JsSdkVO;

/**
 * @author zhoupeipei
 * @date 2019-07-02 15:54
 * @since 1.0.0
 */
@Service
public class JsApiServiceImpl implements IJsApiService {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsApiServiceImpl.class);
    @Autowired
    WeChatConfig weChatConfig;
    @Autowired
    IAccessTokenService accessTokenService;
    private static final String JSAPI_TICKET_KEY = CommonConstant.REDIS_PRE_WECHAT + "JSSDK_TICKET";
    private static final int JSAPI_TICKET_CACHE_TIME = 7000;

    @Override
    public JsSdkVO getJsSdkTicket(String url) throws BusinessException {
        //优先读缓存
        String ticket = RedisUtil.valueOps().getString(JSAPI_TICKET_KEY);
        if (StringUtils.isBlank(ticket)) {
            //缓存没有时，请求微信
            String accessToken = accessTokenService.accessToken();
            JsTicket jsTicket = WeChatApiUtil.getTicket(accessToken);
            //提取返回更新缓存
            if (null == jsTicket.getErrorcode() || 0 == jsTicket.getErrorcode()) {
                ticket = jsTicket.getTicket();
                RedisUtil.valueOps().setString(JSAPI_TICKET_KEY, ticket, JSAPI_TICKET_CACHE_TIME);
            } else {
                LOGGER.error("jsapi-ticket获取失败，{}", jsTicket);
            }
        }
        String noncestr = RandomStringUtils.random(16,true,true);
        long timestamp = DateUtil.getCurrentTimeMillis();
        String signature = SHA1.genWithAmple("jsapi_ticket=" + ticket, "noncestr=" + noncestr, "timestamp=" + timestamp, "url=" + url);
        JsSdkVO jsSdkVO = JsSdkVO.builder()
                                 .appId(weChatConfig.paProperties().getAppId())
                                 .jsapiTicket(ticket)
                                 .noncestr(noncestr)
                                 .timestamp(timestamp)
                                 .url(url)
                                 .signature(signature)
                                 .build();
        return jsSdkVO;
    }
}
